/**
 * Created by hooshim on 2014-12-04.
 */

var G_grid01 = "";
var G_page = 1;
var G_exprsCompCds = "";

$(document).ready(function() {
    fnGetSubMenus();
    fnSetCurMenu(2);
    fnGetLeftMenus('1');
    $("#_curMenu p").html("Express");

    $("#issueDt").datepicker(G_calendar);

    var bodyWidth = $('body').innerWidth();
    bodyWidth = parseInt(bodyWidth,10) - 170;
    $('#_bodyRight').css('width', bodyWidth + 'px');
    fnSetCurMenu(2);
    var gSubMenus = fnGetSubMenus();
    var gScreenHeight = parseInt($(window).height(),10) - 140;
    $("#_bodyLeft").css("height",gScreenHeight);
    $("#_bodyRight").css("height",gScreenHeight);
    gScreenHeight = parseInt(gScreenHeight,10) - 100;
    fnComboExpress('','findExpressCd');
    fnComboExpress('','expressCd');
    fnComboExpressType('cargoType');

    fnSetGrid01(gScreenHeight);
    fnGetList01(1);

    var exprsCompCd =  new Object();
    exprsCompCd["DHL"] = 963;
    exprsCompCd["UPS"] = 962;
    exprsCompCd["TNT"] = 961;
    exprsCompCd["EMS"] = 960;
    G_exprsCompCds = JSON.stringify(exprsCompCd);
});

var fnSetGrid01 = function(h) {

    var grdCd = "grid01";

    var widths = [70, 120, 50, 70, 70, 40, 70, 40, 60, 100, 120, 50, 50, 50];
    var titles = ['발송일', 'BILL NO', 'Express', 'Profit', '화주청구', '입금', '항공지급', '출금', '지역', 'DESTINATION', '화주', 'C/T', 'W/T', 'TYPE'];
    var styles = ['text-align:center;', 'text-align:left;', 'text-align:center;', 'text-align:right;', 'text-align:right;', 'text-align:center;color:#0000CC;', 'text-align:right;', 'text-align:center;color:#CC0000;', 'text-align:center;', 'text-align:center;', 'text-align:left;', 'text-align:center;', 'text-align:right;', 'text-align:center;'];

    var gInfo = new Object();
    gInfo["grdCd"] = "grid01";
    gInfo["title"] = "Express";
    gInfo["widths"] = widths;
    gInfo["titles"] = titles;
    gInfo["styles"] = styles;
    gInfo["function"] = "fnShowExpress";
    gInfo["fullWidth"] = "815";
    gInfo["fullHeight"] = h;
    gInfo["fix"] = "3";

    G_grid01 = JSON.stringify(gInfo);

    fnMkGridInit(G_grid01);
}

var fnShowExpress = function(billCd) {
    fnReset();
    var param  = "billCd="+billCd;
    var valUrl = "./action/express/view.php";
    $('#saveMode').val('update');

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            var dataInfo = data.TBLEXPRESS[0];

            $('#billCd').val(dataInfo.BILLCD);
            $('#issueDt').val(dataInfo.ISSUEDT);
            $('#expressCd').val(dataInfo.EXPRESSCD);
            $('#cargoType').val(dataInfo.CARGOTYPE);
            $('#expressClass').val(dataInfo.EXPRESSCLASS);
            $('#destNationCd').val(dataInfo.DESTNATIONCD);
            $('#destAddr').val(dataInfo.DESTADDR);
            $('#destZone').val(dataInfo.DESTZONE);
            $('#zone').val(dataInfo.ZONENM);
            $('#compCd').val(dataInfo.COMPCD); // 별도 회사 선택 필요
            $('#compNm').val('');
            $('#consignee').val(dataInfo.CONSIGNEE);
            $('#item').val(dataInfo.ITEM);
            $('#cargoTon').val(dataInfo.CARGOTON);
            $('#weightTon').val(dataInfo.WEIGHTTON);
            $('#ratePerWeight').val(dataInfo.RATEPERWEIGHT);
            $('#totalRate').val(dataInfo.TOTALRATE);
            $('#totalRatePerWeight').val(dataInfo.TOTALRATEPERWEIGHT);
            $('#flag').val(dataInfo.FLAG);

            $('#compDCRate').val(dataInfo.COMPDCRATE);
            $('#compOilRate').val(dataInfo.COMPOILRATE);
            $('#compDCAmount').val(dataInfo.COMPDCAMOUNT);
            $('#compInvAmount').val(dataInfo.COMPINVAMOUNT);
            $('#compOilAmount').val(dataInfo.COMPOILAMOUNT);
            $('#compTotalInvAmount').val(dataInfo.COMPTOTALINVAMOUNT);
            $('#compExtraCharge').val(dataInfo.COMPEXTRACHARGE);

            $('#carrDCRate').val(dataInfo.CARRDCRATE);
            $('#carrOilRate').val(dataInfo.CARROILRATE);
            $('#carrDCAmount').val(dataInfo.CARRDCAMOUNT);
            $('#carrInvAmount').val(dataInfo.CARRINVAMOUNT);
            $('#carrOilAmount').val(dataInfo.CARROILAMOUNT);
            $('#carrTotalInvAmount').val(dataInfo.CARRTOTALINVAMOUNT);

            $('#extraCharge').val(dataInfo.EXTRACHARGE);
            $('#profit').val(dataInfo.PROFIT);
            $('#remarks').val(dataInfo.REMARKS);

            var exprsCompCd = $.parseJSON(G_exprsCompCds);
            var expressCompCd = exprsCompCd[dataInfo.EXPRESSCD];
            $('#expressCompCd').val(expressCompCd);

            setTimeout("fnComboCompany('','"+dataInfo.COMPCD+"','compCd','skip');",500);
            fnShadowPop('on');
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });

}

var fnSetExpressCompCd = function() {

    var exprsCompCd = $.parseJSON(G_exprsCompCds);
    var expressCompCd = exprsCompCd[$('#expressCd').val()];
    $('#expressCompCd').val(expressCompCd);

    if (!$('#compCd').val()) { return; }
    var param = "expressCd="+$('#expressCd').val();
    param += "&expressCompCd="+$('#expressCompCd').val();
    param += "&compCd="+$('#compCd').val();
    var valUrl = "./action/express/viewDCRate.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            $("#compDCRate").val(data.DCRATE);
            $("#compOilRate").val(data.OILRATE);
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

var fnGetList = function() {

    if(event.keyCode != "13")
    {
        return; // 엔터일때만 수행
    }
    fnGetList01(1);
}

var fnGetList01 = function(page) {
    fnMkGridLoad(G_grid01);
    if (page) G_page = page;
    else page = G_page;
    var param  = "findBillCd="+$("#findBillCd").val();
    var valUrl = "./action/express/list.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            fnMkGrid(G_grid01,data);
            /*
             $("#table_body").html(list);
             $("#total_rows").html(data.TOTAL_ROW_COUNT);
             var paging = fnPaging('fnGetList', data.TOTAL_ROW_COUNT, page, 10);
             var pages = paging['prev'] + paging['pager'] + paging['next'];
             // alert(pages);
             $("#pager").html(pages);
             */
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

//## BillNo 존재 여부 검사
var fnExistBillCd = function() {

    if ($("#saveMode").val() == "update") {
        return;
    }

    var param  = "billCd="+$("#billCd").val();
    var valUrl = "./action/express/isBillCd.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            var dataExist = data.TBLEXPRESS[0];
            if (dataExist.CNT > 0) {
                alert("이미 등록된 BILL NO 입니다.");
                $("#billCd").focus();
                return
            }
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

//## shadowPop 열기/닫기
var fnShadowPop = function(on) {
    if (on == "on") {
        $("#_shadowPop").css("top","129px");
        $("#_shadowPop").css("left","460px");
        $("#_shadowPop").show('slow');
        $("#billCd").focus();
    }
    else {
        $("#_shadowPop").css("display","none");
    }

}

//## zone 정보 가져오기
var fnGetZone = function(nationCd, clss) {

    if(event.keyCode != "13")
    {
        return; // 엔터일때만 수행
    }

    if (!$("#expressCd").val()) {
        alert('Express를 선택해 주세요!');
        $("#expressCd").focus();
        return;
    }

    $('#zone').val('');
    $('#destZone').val('');
    $('#destAddr').val('');

    var param  = "expressCd="+$("#expressCd").val();
    param += "&nationCd="+nationCd.value;
    param += "&class="+clss;
    var valUrl = "./action/express/listZone.php";
    //window.open(valUrl+'?'+param);

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            if (data.TOTAL_COUNT > 0) {
                var zoneNm = decodeURIComponent(data.TBLZONECD[0].ZONENM);
                var zoneCd = decodeURIComponent(data.TBLZONECD[0].ZONECD);
                var nationNm = decodeURIComponent(data.TBLZONECD[0].NATIONNM);
                $('#zone').val(zoneNm);
                $('#destZone').val(zoneCd);
                $('#destAddr').val(nationNm);
            }
            else
            {
                alert('행당 국가 코드가 없습니다.');
            }
        },
        error: function(data){
            alert('Error!!');
            alert(data.responseText);
        }
    });
}

//## 가격 가져오기
var fnGetRate = function() {

    if(event.keyCode != "13")
    {
        return; // 엔터일때만 수행
    }

    if (!$("#expressCd").val()) {
        alert('Express를 선택해 주세요!');
        $("#expressCd").focus();
        return;
    }
    if (!$("#weightTon").val()) {
        return;
    }
    var param  = "expressCd="+$("#expressCd").val();
    param += "&destZone="+$("#destZone").val();
    param += "&weightTon="+$("#weightTon").val();
    param += "&cargoType="+$("#cargoType").val();
    param += "&class=N";
    var valUrl = "./action/express/listRate.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            if (data.TOTAL_COUNT > 0) {
                var key = data.KEYS.split(",");
                var rate = data.TBLRATEEXPRESS[0][key[0]];
                var weight = data.TBLRATEEXPRESS[0][key[1]];
                var cargoTon = $("#cargoTon").val();
                var weightTon = $("#weightTon").val();
                var expressCd = $("#expressCd").val();
                var TNTstWeight = 30;
                var DHLstWeight = 30;
                var UPSstWeight = 20;
                if (expressCd == "TNT" && weightTon > TNTstWeight)
                {
                    var totalRate = parseInt(rate,10) * parseInt(cargoTon,10) * parseInt(weightTon,10);
                    $("#ratePerWeight").val(fnGetNumWithComma(rate));
                    $("#totalRatePerWeight").val(weight);
                }
                else if (expressCd == "DHL" && weightTon > DHLstWeight)
                {
                    var totalRate = parseInt(rate,10) * parseInt(cargoTon,10) * parseInt(weightTon,10);
                    $("#ratePerWeight").val(fnGetNumWithComma(rate));
                    $("#totalRatePerWeight").val(weight);
                }
                else if (expressCd == "UPS" && weightTon > UPSstWeight)
                {
                    var totalRate = parseInt(rate,10) * parseInt(cargoTon,10) * parseInt(weightTon,10);
                    $("#ratePerWeight").val(fnGetNumWithComma(rate));
                    $("#totalRatePerWeight").val(weight);
                }
                else {
                    var totalRate = parseInt(rate, 10) * parseInt(cargoTon, 10);
                    $("#ratePerWeight").val('');
                    $("#totalRatePerWeight").val('');
                }
                $("#totalRate").val(fnGetNumWithComma(totalRate));
                fnGetProfit();
            }
            else
            {
                alert('가격정보를 찾을수가 없습니다.');
            }
        },
        error: function(data){
            alert('Error!!');
            alert(data.responseText);
        }
    });
}

//## 각 항목 정산 자동 계산
var fnGetProfit = function() {

    if(event.keyCode != "13")
    {
        return; // 엔터일때만 수행
    }

    var totalRate = $('#totalRate').val().split(',').join('');
    if (!totalRate) {
        alert('가격산정을 먼저 해주세요!');
        return;
    }
    var compDCRate = $('#compDCRate').val().split(',').join('');
    if (!compDCRate) compDCRate = 0;
    var compOilRate = $('#compOilRate').val().split(',').join('');
    if (!compOilRate) compOilRate = 0;
    var compDCAmount = $('#compDCAmount').val().split(',').join('');
    if (!compDCAmount) compDCAmount = 0;
    var compOilAmount = $('#compOilAmount').val().split(',').join('');
    if (!compOilAmount) compOilAmount = 0;
    var compInvAmount = $('#compInvAmount').val().split(',').join('');
    if (!compInvAmount) compInvAmount = 0;
    var compTotalInvAmount = $('#compTotalInvAmount').val().split(',').join('');
    if (!compTotalInvAmount) compTotalInvAmount = 0;
    var compExtraCharge = $('#compExtraCharge').val().split(',').join('');
    if (!compExtraCharge) compExtraCharge = 0;
    
    compDCAmount = (parseInt(totalRate,10) * parseFloat(compDCRate,10))/100;
    compDCAmount = Math.ceil(compDCAmount);
    compInvAmount = parseInt(totalRate,10) - parseInt(compDCAmount,10);
    compOilAmount = (parseInt(compInvAmount,10) * parseFloat(compOilRate,10))/100;
    compOilAmount = Math.ceil(compOilAmount);
    compTotalInvAmount = parseInt(totalRate,10) - parseInt(compDCAmount,10) + parseInt(compOilAmount,10) + parseInt(compExtraCharge,10);

    $('#compDCRate').val(fnGetNumWithComma(compDCRate));
    $('#compOilRate').val(fnGetNumWithComma(compOilRate));
    $('#compDCAmount').val(fnGetNumWithComma(compDCAmount));
    $('#compInvAmount').val(fnGetNumWithComma(compInvAmount));
    $('#compOilAmount').val(fnGetNumWithComma(compOilAmount));
    $('#compTotalInvAmount').val(fnGetNumWithComma(compTotalInvAmount));
    
    var carrDCRate = $('#carrDCRate').val().split(',').join('');
    if (!carrDCRate) carrDCRate = 0;
    var carrOilRate = $('#carrOilRate').val().split(',').join('');
    if (!carrOilRate) carrOilRate = 0;
    var carrDCAmount = $('#carrDCAmount').val().split(',').join('');
    if (!carrDCAmount) carrDCAmount = 0;
    var carrOilAmount = $('#carrOilAmount').val().split(',').join('');
    if (!carrOilAmount) carrOilAmount = 0;
    var carrInvAmount = $('#carrInvAmount').val().split(',').join('');
    if (!carrInvAmount) carrInvAmount = 0;
    var carrTotalInvAmount = $('#carrTotalInvAmount').val().split(',').join('');
    if (!carrTotalInvAmount) carrTotalInvAmount = 0;

    carrDCAmount = (parseInt(totalRate,10) * parseFloat(carrDCRate,10))/100;
    carrDCAmount = Math.ceil(carrDCAmount);
    carrInvAmount = parseInt(totalRate,10) - parseInt(carrDCAmount,10);
    carrOilAmount = (parseInt(carrInvAmount,10) * parseFloat(carrOilRate,10))/100;
    carrOilAmount = Math.ceil(carrOilAmount);
    carrTotalInvAmount = parseInt(totalRate,10) - parseInt(carrDCAmount,10) + parseInt(carrOilAmount,10);

    $('#carrDCRate').val(fnGetNumWithComma(carrDCRate));
    $('#carrOilRate').val(fnGetNumWithComma(carrOilRate));
    $('#carrDCAmount').val(fnGetNumWithComma(carrDCAmount));
    $('#carrInvAmount').val(fnGetNumWithComma(carrInvAmount));
    $('#carrOilAmount').val(fnGetNumWithComma(carrOilAmount));
    $('#carrTotalInvAmount').val(fnGetNumWithComma(carrTotalInvAmount));

    var extraCharge = $('#extraCharge').val().split(',').join('');
    if (!extraCharge) extraCharge = 0;
    var profit = parseInt(extraCharge,10) + parseInt(compExtraCharge,10) + parseInt(carrDCAmount,10) + parseInt(compOilAmount,10) - parseInt(compDCAmount,10) - parseInt(carrOilAmount,10);
    $('#profit').val(fnGetNumWithComma(profit));

}

var fnSave = function() {
    if (!$('#billCd').val())
    {
        alert('BILL NO를 입력해 주세요.');
        $('#billCd').focus();
        return;
    }
    if ($('#flag').val() == 'N'){
        if (!confirm("BILL NO: "+$('#billCd').val() + " 건을 정말로 폐기하시겠습니까?"))  {
            return;
        }
    }
    var expressClass = $('#expressClass').val();
    if (expressClass == undefined) expressClass = "N";
    var param = "billCd=" + $('#billCd').val();
    param += "&issueDt=" + $('#issueDt').val();
    param += "&expressCd=" + $('#expressCd').val();
    param += "&cargoType=" + $('#cargoType').val();
    param += "&expressClass=" + expressClass;
    param += "&destNationCd=" + $('#destNationCd').val();
    param += "&destAddr=" + $('#destAddr').val();
    param += "&destZone=" + $('#destZone').val();
    param += "&compCd=" + $('#compCd').val();
    param += "&consignee=" + $('#consignee').val();
    param += "&item=" + $('#item').val();
    param += "&cargoTon=" + $('#cargoTon').val();
    param += "&weightTon=" + $('#weightTon').val().split(',').join('');
    param += "&ratePerWeight=" + $('#ratePerWeight').val().split(',').join('');
    param += "&totalRate=" + $('#totalRate').val().split(',').join('');
    param += "&totalRatePerWeight=" + $('#totalRatePerWeight').val().split(',').join('');
    param += "&flag=" + $('#flag').val();
    param += "&compDCRate=" + $('#compDCRate').val().split(',').join('');
    param += "&compOilRate=" + $('#compOilRate').val().split(',').join('');
    param += "&compDCAmount=" + $('#compDCAmount').val().split(',').join('');
    param += "&compInvAmount=" + $('#compInvAmount').val().split(',').join('');
    param += "&compOilAmount=" + $('#compOilAmount').val().split(',').join('');
    param += "&compTotalInvAmount=" + $('#compTotalInvAmount').val().split(',').join('');
    param += "&compExtraCharge=" + $('#compExtraCharge').val().split(',').join('');
    param += "&carrDCRate=" + $('#carrDCRate').val().split(',').join('');
    param += "&carrOilRate=" + $('#carrOilRate').val().split(',').join('');
    param += "&carrDCAmount=" + $('#carrDCAmount').val().split(',').join('');
    param += "&carrInvAmount=" + $('#carrInvAmount').val().split(',').join('');
    param += "&carrOilAmount=" + $('#carrOilAmount').val().split(',').join('');
    param += "&carrTotalInvAmount=" + $('#carrTotalInvAmount').val().split(',').join('');
    param += "&extraCharge=" + $('#extraCharge').val().split(',').join('');
    param += "&profit=" + $('#profit').val().split(',').join('');
    param += "&remarks=" + $('#remarks').val();
    param += "&expressCompCd=" + $('#expressCompCd').val();
    var exprsCompCd = $.parseJSON(G_exprsCompCds);
    var expressCompCd = exprsCompCd[$('#expressCd').val()];

    var valUrl = "./action/express/save.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            if (data.rsStatus == "Success") {
                alert(data.rsStr);
                fnReset();
                fnGetList01();
            }
            else {
                alert("저장 실패");
            }
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

var fnReset = function() {
    $('#billCd').focus();
    $('#saveMode').val('');
    $('#billCd').val('');
    //$('#issueDt').val('');
    //$('#expressCd').val('');
    //$('#cargoType').val('');
    $('#expressClass').val('');
    $('#destNationCd').val('');
    $('#destAddr').val('');
    $('#destZone').val('');
    $('#zone').val('');
    $('#compCd').val('');
    $('#compNm').val('');
    $('#consignee').val('');
    $('#item').val('');
    $('#cargoTon').val('1');
    $('#weightTon').val('');
    $('#ratePerWeight').val('');
    $('#totalRate').val('');
    $('#totalRatePerWeight').val('');
    $('#flag').val('Y');

    $('#compDCRate').val('');
    $('#compOilRate').val('');
    $('#compDCAmount').val('');
    $('#compInvAmount').val('');
    $('#compOilAmount').val('');
    $('#compTotalInvAmount').val('');
    $('#compExtraCharge').val('');

    $('#carrDCRate').val('');
    $('#carrOilRate').val('');
    $('#carrDCAmount').val('');
    $('#carrInvAmount').val('');
    $('#carrOilAmount').val('');
    $('#carrTotalInvAmount').val('');

    $('#extraCharge').val('');
    $('#profit').val('');
    $('#remarks').val('');
    $('#expressCompCd').val('');

}

var fnCopy = function() {
    $('#saveMode').val('');
    $('#billCd').val('');
}